﻿using System;
using System.Web;
using System.Linq;
using System.Configuration;
using System.Globalization;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.DAL;
using KPIS.GERP.ESS.MODEL;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.APP.App_UI.Forms;
using KPIS.GERP.ESS.APP.SysApprovalService;

namespace KPIS.GERP.ESS.APP.App_UI.UserControls
{
    public partial class RequestAbsencesNew : System.Web.UI.UserControl
    {
        private Main main = new Main();
        private D_Absence absenceDal = new D_Absence();
        private D_HrmEmployees employeesDal = new D_HrmEmployees();
        private SysApprovalService.SysApprovalService approvalService = new SysApprovalService.SysApprovalService();

        protected void Page_Load(object sender, EventArgs e)
        {
            /*  */
            lblSendNewApproval.Visible = new []{"W" }.Contains(Model.record_status) && !IsEditMode;
            lblCheckRuleClient.Visible = IsEditMode;
            lblEdit.Visible = Model.absence_seq != 0 && new[] { "W", "R" }.Contains(Model.record_status) && !IsEditMode;
            lblSave.Visible = IsEditMode;
            IsEditMode = IsEditMode; // repeat ui visibility on page_load
            lblDelete.Visible = new[] { "W" }.Contains(Model.record_status) && !IsEditMode;
            panelMessageSendBackOk.Visible = Model.record_status == "R";
            iframeAbsenceInGims.Attributes["src"] = FrameUrl;
            a1.Attributes["href"] = "~/App_UI/Forms/RequestAbsencesNew.aspx?AbsenceSeq=" + Request["AbsenceSeq"] + "&do=Detail";
            a1.Visible = Request["do"] == "Edit";
            if (IsEditMode && hdfAbsenceSeq.Value != "0" && !string.IsNullOrEmpty(hdfAbsenceSeq.Value))
            {
                ltrHeaderText.Text = "<span style=\"font-size: x-large; color:orange;\">แก้ไข</span>";
            }
            else if (IsEditMode)
            {
                ltrHeaderText.Text = "<span style=\"font-size: x-large; color:green;\">สร้าง</span>";
            }
            else if (!IsEditMode)
            {
                ltrHeaderText.Text = "<span style=\"font-size: x-large; color:blue;\">รายละเอียดคำขอเลขที่ " + hdfAbsenceSeq.Value + "</span>";
            }
        }

        public void LoadData(UiModeEnum mode, M_HrmAbsenceNew model)
        {
            IsEditMode = mode != UiModeEnum.Detail;
            LoadComboboxDatasource();
            Model = model;
        }

        public void LoadComboboxDatasource()
        {
            cbbAbsenceType.Items.Clear(); 
            cbbAbsenceType.SelectedIndex = -1;
            cbbAbsenceType.SelectedValue = null;
            cbbAbsenceType.ClearSelection();

            var data1 = absenceDal.AbsenceTypeList();
            foreach (var data in data1)
            {
                cbbAbsenceType.Items.Add(new ListItem(data.absence_type_name, data.absence_type_seq.ToString()));
            }
            cbbAbsenceType.SelectedIndex = cbbAbsenceType.Items.Count > 0 ? 0 : -1;
        }

        public CheckAbsenceRuleResultVM CheckRuleMessage(string emp_seq, string currentAbsenceSeq, string absence_type_seq,
                                                         string start_date, string end_date, string created_by, string start_time, string end_time)
        {
            int temp_emp_seq, temp_absenceSeq, temp_absence_type_seq, temp_created_by;
            string contact_address = "", description = "", request_title = "";
            Int32.TryParse(emp_seq, out temp_emp_seq);
            Int32.TryParse(currentAbsenceSeq, out temp_absenceSeq);
            Int32.TryParse(absence_type_seq, out temp_absence_type_seq);
            Int32.TryParse(created_by, out temp_created_by);
            DateTime temp_start_date, temp_end_date;
            DateTime.TryParse(start_date, out temp_start_date);
            DateTime.TryParse(end_date, out temp_end_date);

            try
            {
                var reqResponse = approvalService.CheckAbsenceRule(temp_emp_seq, true, temp_absenceSeq, true, temp_absence_type_seq, true, temp_start_date, true,
                                                                   temp_end_date, true, contact_address, description, temp_created_by, true, start_time, end_time, request_title);
                return reqResponse;
            }
            catch (System.Exception ex)
            {
                var e = new System.Exception("Found error on checkrule service : " + approvalService.Url + ":" + ex.Message, ex);
                throw e;
            }
        }

        private string AbsenceTypeName(int? absenceTypeId)
        {
            var absenceType = absenceDal.AbsenceTypeList().FirstOrDefault(o => o.absence_type_seq == absenceTypeId);
            return absenceType != null ? absenceType.absence_type_name : "";
        }

        private string EmployeeFullName(int empId)
        {
            return employeesDal.GetEmployeeFullName(empId);
        }

        private string DateTimeString(DateTime? dt)
        {
            if (dt == null) return "";
            return dt.Value.ToString("dd/MM/yyyy", new CultureInfo("th-TH"));
        } 

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            var model = Model;
                using (var wf = new SysApprovalService.SysApprovalService())
                {
                    var reqData = new CreateTaskVM();
                    reqData.Title = model.request_title;
                    reqData.ApplyToEmpId = model.created_by.Value;
                    reqData.ApplyToEmpIdSpecified = true;
                    reqData.CreateByEmpId = model.created_by.Value;
                    reqData.CreateByEmpIdSpecified = true;
                    reqData.AppPrcGrpId = 1;
                    reqData.AppPrcGrpIdSpecified = true;
                    reqData.RefId = model.absence_seq;
                    reqData.RefIdSpecified = true;
                    reqData.Remark = model.remarks;
                    reqData.ConfirmAs = "P";
                    reqData.ApproveAs = "A";
                    reqData.RefCode = model.ref_no;
                    reqData = wf.CreateTask(reqData);
                    if (!string.IsNullOrEmpty(reqData.CreateErrorResult))
                    {
                        string message = "Error on Wcf.Sys CreateTask() -> " + reqData.CreateErrorResult;
                        message = message.Replace("'", "").Replace("\"", "");
                        main.MessageAlert(Page, message);
                    }
                    else
                    {
                        GoToDetail(model.absence_seq);
                    }
                }
        }

        private int ConvertInt(object obj)
        {
            int result;
            var success = Int32.TryParse(obj == null ? string.Empty : obj.ToString(), out result);
            return result;
        }

        public bool IsEditMode
        {
            get { return !lblRequestTitle.Visible; }
            set
            {
                lblAbsenceType.Visible = !value;
                lblContactAddress.Visible = !value;
                lblDescription.Visible = !value;
                lblEndDate.Visible = !value;
                lblEndTime.Visible = !value;
                lblRequestByEmployee.Visible = true;
                lblRequestTitle.Visible = !value;
                lblStartDate.Visible = !value;
                lblStartTime.Visible = !value;
                lblRecordStatus.Visible = true;
                lblCreatedWhen.Visible = true;
                lblRemark.Visible = true;

                cbbAbsenceType.Visible = value;
                txbRequestTitle.Visible = value;
                dtpStartDate.Visible = value;
                cbbStartTime.Visible = value && !(cbbStartTime.SelectedValue == "M" && cbbEndTime.SelectedValue == "A");
                chbIsFullDay.Visible = value;
                dtpEndDate.Visible = value;
                cbbEndTime.Visible = value && !(cbbStartTime.SelectedValue == "M" && cbbEndTime.SelectedValue == "A");
                txbDescription.Visible = value;
                txbContactAddress.Visible = value;
            }
        }

        public void CopyEditorToDetail()
        {
            var absenceTypeList = absenceDal.AbsenceTypeList(true);
            var absenceTypeSelected = absenceTypeList.FirstOrDefault(o => o.absence_type_seq == Model.absence_type_seq);
            lblAbsenceType.Text = absenceTypeSelected != null ? absenceTypeSelected.absence_type_name : "(ไม่พบ)";
            lblContactAddress.Text = txbContactAddress.Text;
            lblDescription.Text = txbDescription.Text;
            lblRequestTitle.Text = txbRequestTitle.Text;
            lblStartDate.Text = dtpStartDate.GetDateValue().HasValue ? dtpStartDate.GetDateValue().Value.ToString("dd/MM/yyyy") : "";
            lblStartTime.Text = cbbStartTime.SelectedValue == "M" ? "ตั้งแต่ช่วงเช้า" : "ตั้งแต่ช่วงบ่าย";
            lblEndDate.Text = dtpEndDate.GetDateValue().HasValue ? dtpEndDate.GetDateValue().Value.ToString("dd/MM/yyyy") : "";
            lblEndTime.Text = cbbEndTime.SelectedValue == "M" ? "ถึงช่วงเช้า" : "ถึงช่วงบ่าย";
        }

        public M_HrmAbsenceNew Model
        {
            get
            {
                return new M_HrmAbsenceNew
                    {
                        absence_seq = ConvertInt(hdfAbsenceSeq.Value),
                        ref_no = Convert.ToString(hdfRefNo.Value),
                        absence_type_seq = ConvertInt(cbbAbsenceType.SelectedValue),
                        bgm_year = ConvertInt(lblBgmYear.Text),
                        emp_seq = ConvertInt(hdfRequestEmpSeq.Value),
                        request_title = txbRequestTitle.Text,
                        start_date = dtpStartDate.GetDateValue(),
                        start_time = chbIsFullDay.Checked ? "M" : cbbStartTime.SelectedValue,
                        end_date = dtpEndDate.GetDateValue(),
                        end_time = chbIsFullDay.Checked ? "A" : cbbEndTime.SelectedValue,
                        description = txbDescription.Text,
                        contact_address = txbContactAddress.Text,
                        record_status = hdfRecordStatus.Value,
                        created_by = main.ConvertNullInt(hdfRequestEmpSeq.Value),
                        created_when = DateTime.Now,
                        _emp_name = lblRequestByEmployee.Text,
                        day_count = main.ConvertNullInt(lblAmountDay.Text)
                    };
            }

            set
            {
                M_HrmAbsenceNew model = value ?? new M_HrmAbsenceNew();
                hdfAbsenceSeq.Value = Convert.ToString(model.absence_seq);
                if (cbbAbsenceType.Items.Count == 0)
                {
                    LoadComboboxDatasource();
                }
                var item = cbbAbsenceType.Items.FindByValue(Convert.ToString(model.absence_type_seq));
                if (item != null)
                {
                    cbbAbsenceType.SelectedValue = item.Value;
                    //item.Selected = true;
                }

                lblAbsenceType.Text = model._absence_type_name;
                lblBgmYear.Text = model.absence_seq == 0 ? "ตามวันเริ่มลา" : "" +model.bgm_year;
                txbRequestTitle.Text = Convert.ToString(model.request_title);
                dtpStartDate.SetValue(model.start_date);
                lblStartDate.Text = model.start_date.HasValue ? model.start_date.Value.ToString("dd/MM/yyyy") : "";
                cbbStartTime.SelectedValue = Convert.ToString(model.start_time);
                lblStartTime.Text = model.start_time == "M" ? "ตั้งแต่ช่วงเช้า" : "ตั้งแต่ช่วงบ่าย";
                dtpEndDate.SetValue(model.end_date);
                lblEndDate.Text = model.end_date.HasValue ? model.end_date.Value.ToString("dd/MM/yyyy") : "";
                cbbEndTime.SelectedValue = Convert.ToString(model.end_time);
                lblEndTime.Text = model.end_time == "M" ? "ถึงช่วงเช้า" : "ถึงช่วงบ่าย";
                if (model.start_time == "M" && model.end_time == "A")
                {
                    chbIsFullDay.Checked = true;
                    cbbStartTime.Visible = false;
                    cbbEndTime.Visible = false;
                }
                else
                {
                    chbIsFullDay.Checked = false;
                    cbbStartTime.Visible = true;
                    cbbEndTime.Visible = true;
                }

                txbDescription.Text = model.description;
                lblDescription.Text = model.description;
                txbContactAddress.Text = model.contact_address;
                lblContactAddress.Text = model.contact_address;
                hdfRecordStatus.Value = model.record_status;
                switch (model.record_status)
                {
                    case "C":
                        lblRecordStatus.Text = "ยกเลิก";
                        break;
                    case "D":
                        lblRecordStatus.Text = "ถูกลบ";
                        break;
                    case "W":
                        lblRecordStatus.Text = "ยังไม่ส่งขออนุมัติ";
                        break;
                    case "P":
                        lblRecordStatus.Text = "ระหว่างรออนุมัติ";
                        break;
                    case "A":
                        lblRecordStatus.Text = "ผ่านอนมุัติแล้ว";
                        break;
                    case "U":
                        lblRecordStatus.Text = "ใช้งานอยู่";
                        break;
                    case "J":
                        lblRecordStatus.Text = "ไม่ผ่านการอนุมัติ";
                        break;
                    case "R":
                        lblRecordStatus.Text = "ถูกส่งกลับให้แก้ไข";
                        break;
                    default:
                        lblRecordStatus.Text = model.record_status;
                        break;
                }
                lblCreatedWhen.Text = model.created_when.HasValue ? model.created_when.Value.ToString("dd/MM/yyyy HH:mm") : "-";
                hdfRequestEmpSeq.Value = Convert.ToString(model.emp_seq);
                panelAbsenceSeq.Visible = model.absence_seq != 0;
                ltrAbsenceSeq.Text = model.absence_seq.ToString();
                hdfRefNo.Value = model.ref_no;
                ltrRefNo.Text = model.ref_no;
                lblRequestByEmployee.Text = model._emp_name;
                lblRemark.Text = model.remarks;
                lblAmountDay.Text = Convert.ToString(model.day_count);
                CopyEditorToDetail();
            }
        }

        protected string FrameUrl
        {
            get
            {
                string subSystem = ConfigurationSettings.AppSettings["SubSystem"];
                subSystem = !string.IsNullOrEmpty(subSystem) ? "/" + subSystem : "";
                var s = HttpContext.Current.Request.Url.Host + subSystem;
                var f = "http://{0}/WEB.GIMS/Home/SingleSigonCookie?redirectpage=//{0}/WEB.GIMS/Task/FindDetails''QnoLayout=true''NappPrcGrpId={1}''NrefId={2}&isEncode64=false";
                var url = string.Format(f, s, 1, Model.absence_seq);
                return url;
            }
        }

        protected void chbIsFullDay_CheckedChanged(object sender, EventArgs e)
        {
            if (chbIsFullDay.Checked)
            {
                cbbStartTime.Visible = cbbEndTime.Visible = false;
            }
            else
            {
                cbbStartTime.Visible = cbbEndTime.Visible = true;
            }
        }

        protected void btnIndex_Click(object sender, EventArgs e)
        {
            GoToIndex();
        }

        protected void lblEdit_Click(object sender, EventArgs e)
        {
            GoToEdit(Convert.ToInt32(hdfAbsenceSeq.Value));
        }

        protected void lblSave_Click(object sender, EventArgs e)
        {
            var model = Model;
            CheckAbsenceRuleResultVM reqResponse;
            string resultMessage;

            reqResponse = approvalService.CheckAbsenceRule(model.emp_seq.Value, true, model.absence_seq, true, model.absence_type_seq.Value, true,
                                                           model.start_date.Value, true, model.end_date.Value, true, model.contact_address,
                                                           model.description, model.created_by.Value, true, model.start_time,
                                                           model.end_time, model.request_title);

            resultMessage = reqResponse.Remarks;
            if (reqResponse.IsError)
            {
                main.MessageAlert(Page, resultMessage);
                return;
            }
            else
            {
                var wf = new SysApprovalService.SysApprovalService();
                CheckAbsenceRuleResultVM reqResponse2;
                if (reqResponse.AbsenceId == null || reqResponse.AbsenceId == 0)
                {
                    reqResponse2 = wf.InsertAbsence(reqResponse, model.contact_address, model.description, model.request_title, SsMng.EmpSeqI, false);
                }
                else
                {
                    reqResponse2 = wf.UpdateAbsence(reqResponse, model.contact_address, model.description, model.request_title, SsMng.EmpSeqI, false);
                }

                model.absence_seq = reqResponse2.AbsenceId ?? 0;
                Model = model;
                GoToDetail(Model.absence_seq);
            }
        }

        public string FormValidate()
        {
            if (string.IsNullOrEmpty(Model.request_title))
            {
                return "กรุณากรอกหัวข้อคำขอ";
            }
            if (!Model.absence_type_seq.HasValue)
            {
                return "กรุณาเลือกประเภทการลา";
            }
            if (!Model.start_date.HasValue)
            {
                return "กรุณาเลือกวันเริ่มลา";
            }
            if (!Model.end_date.HasValue)
            {
                return "กรุณาเลือกวันสุดท้ายของการลา";
            }
            if (Model.end_date.Value.Subtract(Model.start_date.Value).Seconds < 0)
            {
                return "วันสิ้นสุดต้องไม่น้อยกว่าวันเริ่ม";
            }
            return "";
        }

        public void GoToIndex()
        {
            Response.Redirect("RequestAbsencesNew.aspx");
        }

        public void GoToEdit(int absenceSeq)
        {
            Response.Redirect("RequestAbsencesNew.aspx?AbsenceSeq=" + absenceSeq + "&do=Edit");
        }

        public void GoToDetail(int absenceSeq)
        {
            Response.Redirect("RequestAbsencesNew.aspx?AbsenceSeq=" + absenceSeq + "&do=Detail");
        }

        protected void lblDelete_Click(object sender, EventArgs e)
        {
            absenceDal.DeleteHrmPsAbsence(Model.absence_seq, SsMng.EmpSeqI);
            Response.Redirect("RequestAbsencesNew.aspx");
        }

    }
}